using System.Globalization;
using MyPet.Common;
using MyPet.Models;
using NetDimension.DianDian;
using NetDimension.Json;

namespace MyPet
{
    using System;
    using CrystalQuartz.Core.SchedulerProviders;
    using Quartz;

    public class SimpleSchedulerProvider : StdSchedulerProvider
    {
        protected override System.Collections.Specialized.NameValueCollection GetSchedulerProperties()
        {
            var properties = base.GetSchedulerProperties();
            // Place custom properties creation here:
            //     properties.Add("test1", "test1value");
            return properties;
        }

        protected override void InitScheduler(IScheduler scheduler)
        {
            // Put jobs creation code here

            // Sample job
            //var jobDetail = JobBuilder.Create<HelloJob>()
            //    .StoreDurably()
            //    .WithIdentity("myJob")
            //    .Build();

            //var trigger = TriggerBuilder.Create()
            //    .WithIdentity("myTrigger")
            //    .StartNow()
            //    .WithSimpleSchedule(x => x.WithIntervalInMinutes(1).RepeatForever())
            //    .Build();

            //scheduler.ScheduleJob(jobDetail, trigger);

            TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("China Standard Time");
            IJobDetail jobDetail = JobBuilder.Create<HelloJob>().StoreDurably().WithIdentity("myJob").Build();
            ITrigger trigger = TriggerBuilder.Create().WithIdentity("myTrigger").StartNow().WithCronSchedule(MyConfig.GetValue("CronExpression"), x => x.InTimeZone(timeZoneInfo)).Build();
            scheduler.ScheduleJob(jobDetail, trigger);
        }

        internal class HelloJob : IJob
        {
            public void Execute(IJobExecutionContext context)
            {
                string updateKey = MyConfig.GetValue("UpdateKey");
                string updateType = MyConfig.GetValue("UpdateType");
                string updateTable = MyConfig.GetValue("UpdateTable");

                var oauth = new OAuth("**", "**", "");
                oauth.GetAccessTokenByPassword("**", "**");
                var sinaNew = new Client(oauth);
                string sinceId = MyConfig.GetValue("UpdatePostID");
                int limit = int.Parse(MyConfig.GetValue("UpdateCount")) + 1;
                string result = sinaNew.API.Entity.Dian.Tags(sinaNew.OAuth.AccessToken, limit, updateKey, 0, sinceId, true, true, "html");
                dynamic newValue = JsonConvert.DeserializeObject<object>(result);
                dynamic testResult = newValue["response"]["posts"];
                int countResult = 0;
                int tempResult = 0;
                int i = 0;
                while (true)
                {
                    if (i >= testResult.Count)
                    {
                        break;
                    }
                    if (testResult[i]["type"].ToString() == "photo")
                    {
                        countResult++;
                    }
                    i++;
                }
                if (testResult[0]["type"].ToString() == "photo")
                {
                    countResult--;
                }
                i = 1;
                while (true)
                {
                    if (i >= testResult.Count)
                    {
                        break;
                    }
                    if (testResult[i]["type"].ToString() == "photo")
                    {
                        tempResult++;
                        var doc = new PetPhoto();
                        string postIdStr = testResult[i]["postId"].ToString();
                        doc.postId = postIdStr;
                        doc.type = "photo";
                        dynamic empty = testResult[i]["caption"] == (dynamic)null ? string.Empty : testResult[i]["caption"].ToString();
                        var captionStr = empty;
                        doc.caption =
                            captionStr.StripHtml()
                                .Replace("<p>", "")
                                .Replace("</p>", "")
                                .Replace("<em>", "")
                                .Replace("</em>", "");
                        doc.photo = testResult[i]["photos"][0]["altSizes"]["default"]["url"].ToString();
                        doc.photo = doc.photo.Replace("libdd", "srcdd");
                        doc.photos = testResult[i]["photos"][0].ToString();
                        var tagStr = testResult[i]["tags"].ToString();
                        doc.tags = tagStr.Replace("[", "").Replace("]", "");
                        doc.likeCount = int.Parse(testResult[i]["likeCount"].ToString());
                        doc.createTime = testResult[i]["createTime"].ToString();
                        doc.blogUuid = testResult[i]["blogUuid"].ToString();
                        doc.postUrl = testResult[i]["postUrl"].ToString();
                        MongoDBHelper.MongoDBHelper.InsertOne(updateTable, doc);
                        MongoDBHelper.MongoDBHelper.InsertOne(updateType, doc);
                        if (tempResult == countResult)
                        {
                            MyConfig.SetValue("UpdateTime", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                            MyConfig.SetValue("UpdatePostID", postIdStr);
                        }
                    }
                    i++;
                }
            }
        }
    }
}